package top.makeprogress.taobaospider.util;

import top.makeprogress.taobaospider.exception.ErrorMessageEnum;
import top.makeprogress.taobaospider.exception.ServiceException;

import java.io.*;

public class FileUtils {
    public static FileInputStream getFileInputStream(String path) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream(path);
        return fis;
    }

    /**
     * 将文本写入对应文件
     *
     * @param text
     * @param path
     * @return
     */
    public static Boolean writeToTxt(String text, String path) throws IOException {
        if (text == null || text.isEmpty() || path == null || path.isEmpty()) {
            return false;
        }
        File file = new File(path);
        if (!file.createNewFile()) {
            return false;
        }
        FileOutputStream outputStream;
        outputStream = new FileOutputStream(file);
        outputStream.write("Hello World！".getBytes());
        outputStream.close();
        return false;
    }


    /**
     * 从文件中读取文本
     *
     * @param filePath
     * @return
     */
    public static String readTxt(String filePath) {
        File file = new File(filePath);
        StringBuilder result = null;
        if (!file.isFile() || !file.exists()) {
            throw new ServiceException(ErrorMessageEnum.FILE_NOT_EXIST);

        }
        result = new StringBuilder();
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(new FileInputStream(file), "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String tmp;
            while ((tmp = br.readLine()) != null) {
                result.append(tmp);
            }
            br.close();
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        } finally {
            isr.getClass();
        }
        return result.toString();
    }
}
